using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;
using System.Web;

using ECCIT.Web.Configuration;

namespace ECCIT.Web.UI.WebControls
{
	/// <summary>
	/// Summary description for ELPButton.
	/// </summary>
	[DefaultProperty("AllowCustomStyle"),
       ToolboxData("<{0}:YUITreeView runat=server></{0}:YUITreeView>")]
    public class YUITreeView : System.Web.UI.WebControls.WebControl
	{
		private bool _allowCustomStyle = false;

		[Bindable(true), 
		Category("Appearance"), 
		DefaultValue(false)] 
		public bool AllowCustomStyle
		{
			get {return _allowCustomStyle;}
			set {_allowCustomStyle = value;}
		}

		/// <summary> 
		/// Render this control to the output parameter specified.
		/// </summary>
		/// <param name="output"> The HTML writer to write out to </param>
		protected override void Render(HtmlTextWriter output)
		{						
			// render style
			if (!_allowCustomStyle)
			{
				StringBuilder styleBuilder = new StringBuilder("<style type=\"text/css\">");
				styleBuilder.Append("#").Append(this.ID).Append(" {font-family:Courier New;font-size:x-small;}\n");
				styleBuilder.Append("</style>\n");
				output.Write(styleBuilder.ToString());
			}

			// render control
			output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
			base.AddAttributesToRender(output);
			output.RenderBeginTag(HtmlTextWriterTag.Div);
			output.RenderEndTag();
			//base.Render(output);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
			string scriptKey = "ELPTreeView_Script";
			if (!this.Page.IsClientScriptBlockRegistered(scriptKey))
			{					
				string registerScript = BuildStyleSheetBlock((string[])StyleSheetManager.StyleSheets["TreeView"]);
				registerScript += BuildClientScriptBlock((string[])JavaScriptManager.Scripts["TreeView"]);
				this.Page.RegisterClientScriptBlock(scriptKey, registerScript);
			}
		}

		private string BuildStyleSheetBlock(string[] styleSheets)
		{
			string styleSheetBlock = string.Empty;
			if (styleSheets != null)
			{
                string virtualDir = (this.Page is IBasePage) ? ((IBasePage)this.Page).ApplicationVirtualDirectory : "../";
				foreach (string styleSheet in styleSheets)
					styleSheetBlock += "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + virtualDir + styleSheet + "\">";
			}

			return styleSheetBlock;
		}

		private string BuildClientScriptBlock(string[] clientScripts)
		{
			string clientScriptBlock = string.Empty;
			if (clientScripts != null)
			{
                string virtualDir = (this.Page is IBasePage) ? ((IBasePage)this.Page).ApplicationVirtualDirectory : "../";
				foreach (string clientScript in clientScripts)
					clientScriptBlock += "<script language=javascript src='" + virtualDir + clientScript + "'></script>";
			}

			return clientScriptBlock;
		}
	}
}
